<!-- 基础设置--点位管理页面 -->
<template>
  <div>
    <div v-show="isMain" class="equip-wrap-common">
      <px-form class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
        <px-row :gutter="16">
          <px-col :span="6">
            <px-form-item label="指标名称">
              <px-input
                v-model="queryParams.measureName"
                clearable
                placeholder="请输入"
                maxlength="50"
                @blur="queryParams.measureName = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="指标编码">
              <px-input
                v-model="queryParams.measureCode"
                clearable
                placeholder="请输入"
                maxlength="50"
                @blur="queryParams.measureCode = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="点位编码">
              <px-input
                v-model="queryParams.tagCode"
                clearable
                placeholder="请输入"
                maxlength="200"
                @blur="queryParams.tagCode = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="是否计算">
              <px-select v-model="queryParams.isNeedCalculate" filterable placeholder="请选择" clearable>
                <px-option v-for="(item, index) in isNeedCalculateList" :key="index" :label="item.label" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="指标类型">
              <px-select v-model="queryParams.measureTypeCode" filterable clearable placeholder="请选择" style="width: 100%">
                <px-option v-for="item in measureTypeCodeList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="创建人">
              <px-select-v2 v-model="queryParams.createBy" filterable clearable :options="createByList" placeholder="请选择" />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <EquipClassSelect :className="queryParams.className" @changeClassName="changeClassName" />
          </px-col>
          <px-col :span="6">
            <px-form-item label="指标来源">
              <px-select v-model="queryParams.measureSource" filterable clearable placeholder="请选择">
                <px-option v-for="item in measureSourceList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <!-- <px-col :span="6">
            <px-form-item label="发布状态">
              <px-select v-model="queryParams.isMaintain" placeholder="请选择">
                <px-option v-for="(item, index) in isConstantList" :key="index" :label="item.label" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col> -->
          <px-col :span="6">
            <px-button type="primary" @click="queryTable">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <div class="equip-table-btn">
        <px-button v-has="'SYSTEM_BASE_MEASURE_MANAGE_ADD'" style="margin-right: 8px" type="primary" @click="addSpareParts">新增</px-button>
        <px-button v-has="'SYSTEM_BASE_MEASURE_MANAGE_EXPORT'" icon="Upload" plain style="margin-right: 8px" type="primary" @click="handleExport">
          导出
        </px-button>
        <px-button
          v-has="'SYSTEM_BASE_MEASURE_MANAGE_DOWNLOAD'"
          icon="Download"
          plain
          style="margin-right: 8px"
          type="primary"
          @click="templateDownload"
        >
          下载模板
        </px-button>
        <px-upload
          v-has="'SYSTEM_BASE_MEASURE_MANAGE_BATCH_UPLOAD'"
          action="#"
          :http-request="handleImport"
          :show-file-list="false"
          accept=".xlsx, xls"
        >
          <px-button type="primary" icon="Upload">批量导入</px-button>
        </px-upload>
        <div style="flex: 1; text-align: right">
          <px-button
            v-has="'SYSTEM_BASE_MEASURE_VERIFY_BTN'"
            style="margin-right: 8px"
            type="primary"
            plain
            @click="showIndicatorVerifyDialog = true"
          >
            指标验证
          </px-button>
          <px-button v-has="'SYSTEM_BASE_MEASURE_PID_BTN'" type="primary" plain @click="showPidDialog = true">PID管理</px-button>
        </div>
        <px-button v-has="'SYSTEM_BASE_MEASURE_MANAGE_TAG'" icon="Flag" plain style="margin-left: 8px" type="primary" @click="isTagShow = true">
          标注标签
        </px-button>
      </div>
      <px-table :data="tableData" class="equip-table" height="calc(100vh - 378px)" border @selection-change="selectionChange">
        <px-table-column type="selection" min-width="40" align="center" />
        <px-table-column type="index" label="序号" width="60" align="center" fixed="left" />
        <px-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :align="item.align"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template v-if="item.type === 'cycle'" #default="scope">
            {{ scope.row.statisticsCycleDesc?.join(",") }}
          </template>
          <template v-else-if="item.type === 'calc'" #default="scope">
            <px-button v-if="scope.row.isNeedCalculate" type="primary" link @click="handleShowCalc(scope.row)">查看</px-button>
            <span v-else>-</span>
          </template>
          <template v-else-if="item.type === 'tag'" #default="scope">
            <px-tag v-for="(item, index) in scope.row.measureTagsDesc" :key="index" class="mr-2">{{ item }}</px-tag>
          </template>
          <template v-else #default="scope">{{
            scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
          }}</template>
        </px-table-column>
        <px-table-column fixed="right" label="操作" min-width="144" align="center">
          <template #default="scope">
            <px-tooltip content="详情" placement="top">
              <px-button v-has="'SYSTEM_BASE_MEASURE_MANAGE_VIEW'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
            </px-tooltip>
            <px-tooltip content="编辑" placement="top">
              <px-button v-has="'SYSTEM_BASE_MEASURE_MANAGE_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
            </px-tooltip>
            <px-tooltip content="删除" placement="top">
              <px-button v-has="'SYSTEM_BASE_MEASURE_MANAGE_DEL'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <!-- 详情新增/编辑页面 -->
    <AddMeasureDetail
      :isMain="isMain"
      :isView="isView"
      :drawerType="drawerType"
      :measureCode="measureCode"
      :username="username"
      @queryTable="queryTable"
      @backMainPage="backMainPage"
    />
    <!-- 详情查看页面 -->
    <ViewMeasureDetail :isMain="isMain" :isView="isView" :measureCode="measureCode" @backMainPage="backMainPage" />
    <px-dialog v-model="isCalcShow" :title="rowData.measureName" destroy-on-close @close="handleClose">
      <div class="calc-dialog">
        <p>
          计算公式：<span>{{ rowData.calculateFormula }}</span>
        </p>
        <p>
          所需点位：<span>{{ rowData.tagCodes }}</span>
        </p>
        <p>
          需要积分点位：<span>{{ rowData.integralTagCodes }}</span>
        </p>
        <p>
          需要作差点位：<span>{{ rowData.minusTagCodes }}</span>
        </p>
      </div>
    </px-dialog>
    <px-dialog v-model="showIndicatorVerifyDialog" class="large-dialog" title="指标验证" destroy-on-close width="80%" @close="handleClose">
      <indicatorVerify />
    </px-dialog>
    <px-dialog v-model="showPidDialog" class="large-dialog" title="PID管理" destroy-on-close width="80%" @close="handleClose">
      <pidManage />
    </px-dialog>
    <AddTagDialog :visible="isTagShow" @closeDialog="isTagShow = false" @queryTable="queryTable" />
    <ErrorDialog :visible="isErrorShow" :errData="errData" @closeErrDialog="closeErrDialog" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "SYSTEM_BASE_MEASURE"
});
import { queryDictData } from "@/api/common";
import { deleteMeasure, getMeasureImport, pageMeasureList } from "@/api/system/measure";
import { useNav } from "@/layout/hooks/useNav";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, onMounted, reactive, toRefs } from "vue";
import indicatorVerify from "../indicatorVerify/index.vue";
import pidManage from "../pid/index.vue";
import AddMeasureDetail from "./components/AddMeasureDetail.vue";
import AddTagDialog from "./components/AddTagDialog.vue";
import ErrorDialog from "./components/ErrorDialog.vue";
import ViewMeasureDetail from "./components/ViewMeasureDetail.vue";

const { proxy }: any = getCurrentInstance();

const { username } = useNav();
const state = reactive<any>({
  isMain: true, // 主页面true 详情页面false
  isView: true, // 查看true 新增/编辑false
  measureTypeCodeList: [],
  isNeedCalculateList: [
    {
      value: 1,
      label: "是"
    },
    {
      value: 0,
      label: "否"
    }
  ],
  createByList: [],
  isConstantList: [
    {
      value: 1,
      label: "是"
    },
    {
      value: 0,
      label: "否"
    }
  ],
  queryParams: {
    measureName: "",
    tagCode: "",
    measureCode: "",
    isNeedCalculate: "",
    measureTypeCode: "",
    createBy: "",
    className: "",
    measureSource: "",
    isMaintain: "",
    pageNum: 1,
    pageSize: 20
  },
  tableColumns: [
    { prop: "measureCode", label: "指标编码", minWidth: "180", showOverflowTooltip: true, fixed: "left" },
    { prop: "measureName", label: "指标名称", minWidth: "180", showOverflowTooltip: true },
    { prop: "isNeedCalculateDesc", label: "需要计算", minWidth: "90", showOverflowTooltip: true },
    { prop: "calculateFormula", label: "计算公式", minWidth: "90", showOverflowTooltip: true, type: "calc" },
    { prop: "measureUnitDesc", label: "指标单位", minWidth: "100", showOverflowTooltip: true },
    { prop: "decimalPlaces", label: "保留位数", minWidth: "90", showOverflowTooltip: true },
    { prop: "tagCode", label: "绑定点位编码", minWidth: "180", showOverflowTooltip: true },
    { prop: "measureTypeCodeDesc", label: "指标类型", minWidth: "90", showOverflowTooltip: true },
    { prop: "isDerivedDesc", label: "生成衍生指标", minWidth: "110", showOverflowTooltip: true },
    // { prop: "isDerivedDesc", label: "是否衍生指标", minWidth: "110", showOverflowTooltip: true },
    // { prop: "statisticsCycleDesc", label: "衍生指标统计周期", minWidth: "150", type: "cycle", showOverflowTooltip: true },
    { prop: "monitorEntityTypeDesc", label: "监控实体类型", minWidth: "120", showOverflowTooltip: true },
    { prop: "monitorEntityIdDesc", label: "监控实体", minWidth: "120", showOverflowTooltip: true },
    { prop: "monitorMaterialIdDesc", label: "监控物料", minWidth: "120", showOverflowTooltip: true },
    { prop: "measureSourceDesc", label: "指标来源", minWidth: "90", showOverflowTooltip: true },
    { prop: "classNameDesc", label: "科室", minWidth: "80", showOverflowTooltip: true },
    { prop: "positionNameAll", label: "物理位置信息", minWidth: "150", showOverflowTooltip: true },
    // { prop: "positionNameAll", label: "发布状态", minWidth: "100", showOverflowTooltip: true },
    { prop: "measureTagsDesc", label: "标签", minWidth: "100", showOverflowTooltip: true, type: "tag" },
    { prop: "createByName", label: "创建人", minWidth: "120", showOverflowTooltip: true },
    { prop: "createTime", label: "创建时间", minWidth: "150", showOverflowTooltip: true },
    { prop: "updateByName", label: "修改人", minWidth: "120", showOverflowTooltip: true },
    { prop: "updateTime", label: "修改时间", minWidth: "150", showOverflowTooltip: true }
  ],
  tableData: [],
  total: 0,
  selectIds: [],
  drawerType: "add",
  isCalcShow: false, // 公式弹窗是否可见
  rowData: {},
  measureCode: "", // 指标编码，根据它获取详情
  systemCodeList: [],
  measureSourceList: [],
  showIndicatorVerifyDialog: false, // 指标验证弹框
  showPidDialog: false, // PID管理弹框
  isTagShow: false,
  isErrorShow: false,
  errData: {}
});
const {
  isMain,
  isView,
  measureTypeCodeList,
  isNeedCalculateList,
  isConstantList,
  selectIds,
  createByList,
  queryParams,
  tableColumns,
  tableData,
  total,
  isCalcShow,
  rowData,
  drawerType,
  measureCode,
  systemCodeList,
  measureSourceList,
  showIndicatorVerifyDialog,
  showPidDialog,
  isTagShow,
  isErrorShow,
  errData
} = toRefs(state);

// 表格多选框选中
const selectionChange = (val: any) => {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.measureCode) {
      selectIds.value.push(item.measureCode);
    }
  });
};

// 进入页面时触发
onMounted(() => {
  queryTable();
  queryTagUnitList();
  queryRecipientIdSelect();
});
//创建人下拉,获取contactName
const queryRecipientIdSelect = async () => {
  createByList.value = await getEmployeeIdAndName();
  // console.log(contactNameList.value)
};
//指标类型/指标来源下拉框
const queryTagUnitList = async () => {
  const tempClassNameList1 = await queryDictData({ typeCode: "MEASURE_TYPE" });
  measureTypeCodeList.value = tempClassNameList1 || [];
  const tempClassNameList = await queryDictData({ typeCode: "MEASURE_SOURCE" });
  measureSourceList.value = tempClassNameList || [];
};

// 导出
const handleExport = () => {
  if (selectIds.value.length == 0) {
    PxMessage.warning("请选择指标后操作");
    return;
  }
  const params = {
    codes: selectIds.value
  };
  proxy.download("post", "/account/api/v1/measure/exportMeasure", params);
};

// 下载模版
const templateDownload = async () => {
  proxy.download("post", "/account/api/v1/measure/importMeasureTemplate", {});
};

const closeErrDialog = () => {
  errData.value = {};
  isErrorShow.value = false;
};

const handleImport = async (options: any) => {
  try {
    const { file } = options;
    const formData = new FormData();
    formData.append("file", file);
    const res = await getMeasureImport(formData);
    if (res?.result) {
      PxMessage.success("批量导入成功");
      queryTable();
    } else {
      console.log("hshhh");
      isErrorShow.value = true;
      errData.value = res;
    }
  } catch (error) {
    console.log(error);
  }
};

// 查询备件列表
const queryTable = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  const data = await pageMeasureList(params);
  tableData.value = data?.data || [];
  total.value = data?.total;
};
// 重置筛选条件和备件列表
const resetTable = async () => {
  queryParams.value = {
    measureName: "",
    tagCode: "",
    measureCode: "",
    isNeedCalculate: "",
    measureTypeCode: "",
    createBy: "",
    className: "",
    measureSource: "",
    isMaintain: "",
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  queryTable();
};

// 计算公式弹窗的打开和关闭
const handleShowCalc = row => {
  isCalcShow.value = true;
  rowData.value = row;
};
const handleClose = () => {
  isCalcShow.value = false;
  rowData.value = {};
};

// 查看备件详情
const handleView = (row: any) => {
  drawerType.value = "view";
  measureCode.value = row.measureCode;
  isMain.value = false;
  isView.value = true;
};
// 添加备件详情
const addSpareParts = () => {
  drawerType.value = "add";
  isMain.value = false;
  isView.value = false;
};
// 编辑备件详情
const handleEdit = (row: any) => {
  drawerType.value = "edit";
  measureCode.value = row.measureCode;
  isMain.value = false;
  isView.value = false;
};
// 从新增/编辑、详情返回主页面
const backMainPage = () => {
  isMain.value = true;
  isView.value = false;
  measureCode.value = "";
};
// 删除
const handleDelete = (row?: any) => {
  PxMessageBox.confirm(`删除后不可恢复，继续删除吗？`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await deleteMeasure({ id: row.id });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};

// 科室组件调用父组件
const changeClassName = val => {
  queryParams.value.className = val;
  queryParams.value.systemCode = "";
  systemCodeList.value = [];
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");

.calc-dialog {
  p {
    line-height: 2;
    color: #333;

    span {
      color: #666;
      word-break: break-word;
    }
  }
}

:deep(.large-dialog) {
  margin-top: 60px;
}
</style>
